/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moyu.sql.business.entity.MoyuRouter;
import com.moyu.sql.business.entity.vo.MoyuRouterTree;
import com.moyu.sql.business.mapper.MoyuRouterMapper;
import com.moyu.sql.business.service.IMoyuRouterService;
import com.moyu.sql.business.service.IMoyuSqlExecuteService;
import jakarta.annotation.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import java.util.Map;

@Service
public class MoyuRouterServiceImpl extends ServiceImpl<MoyuRouterMapper, MoyuRouter> implements IMoyuRouterService {

    @Resource
    private IMoyuSqlExecuteService moyuSqlExecuteService;

    /**
     * 根据路由路径和请求参数执行路由信息并返回
     *
     * @param routerFullPath 路由完整路径
     * @param requestMethod  请求方法
     * @param paramsMap      请求参数
     * @return 路由执行结果
     */
    @Override
    public Object execute(String routerFullPath, HttpMethod requestMethod, Map<String, Object> paramsMap) {
        MoyuRouter moyuRouter = getByFullPathAndMethod(routerFullPath, RequestMethod.resolve(requestMethod));
        if (ObjectUtils.isEmpty(moyuRouter)) {
            // 抛出404
            throw new RuntimeException();
        }
        return moyuSqlExecuteService.execute(moyuRouter.getSqlId(), paramsMap);
    }

    /**
     * 获取所有请求路由
     *
     * @return 请求路由列表
     */
    @Override
    public List<MoyuRouter> getReuqestRouterList() {
        return this.lambdaQuery()
                .eq(MoyuRouter::getIsRequest, true)
                .list();
    }

    /**
     * 根据路由完整路径和请求方法获取路由信息
     *
     * @param routerFullPath 路由完整路径
     * @param requestMethod  请求方法
     * @return 路由信息
     */
    @Override
    public MoyuRouter getByFullPathAndMethod(String routerFullPath, RequestMethod requestMethod) {
        return this.lambdaQuery()
                .eq(MoyuRouter::getRouterFullPath, routerFullPath)
                .eq(MoyuRouter::getRequestMethod, requestMethod)
                .one();
    }

    /**
     * 获取路由树
     *
     * @return 路由树
     */
    @Override
    public List<MoyuRouterTree> getRouterTree() {
        return this.baseMapper.selectRouterTree();
    }
}
